package com.marvels.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.marvels.approve.common.utils.ApplicationContextAchieve;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.MarvelsUtils;
import com.marvels.common.utils.ThreadContextUtil;
import com.marvels.system.permission.dao.AccessBarredIpMapper;

/**
 * IP拦截
 * @author wujunfeng
 *
 */
public class MarvelsIPInterceptor implements HandlerInterceptor {

	private AccessBarredIpMapper accessBarredIpMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String ip = MarvelsUtils.getIpAddr(request);
		try {
			ApplicationContext applicationContext = ApplicationContextAchieve.getApplicationContext();
			accessBarredIpMapper = applicationContext.getBean(AccessBarredIpMapper.class);
			int count = accessBarredIpMapper.selectAccessBarredIp(ip);
			// 大于0 说明存在封禁记录
			if(count > 0){
				response.setContentType(MarvelsConstant.CONTENT_TYPE_JSON);
				MarvelsResultDTO result = MarvelsResultDTO.getResult(MarvelsErrorCode.UNKNOWN_ERROR.getValue(), MarvelsErrorCode.UNKNOWN_ERROR.getDesc(), null);
				response.getWriter().print(JSONObject.toJSONString(result));
				MarvelsLogUtil.getInstance().info("IP：" + ip + "，已被系统自动拦截");
				return false;
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("IP：" + ip + "，拦截过滤器报错，自动放行");
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		ThreadContextUtil.removeAll();
	}
	
}
